/*
 * @Author: shaohh // 时间控件
 * @Date: 2022-10-20 09:54:02 
 * @Last Modified by: shaohh
 * @Last Modified time: 2022-11-22 17:29:08
 */
<template>
	<div class="component_search_form_date clearfix">
		<!-- <el-radio-group v-model="curType" :size="moduleSize" style="float: left;" @change="radioChange">
			<el-radio-button v-for="item in showBtnList" :key="item.value" :label="item.value">{{ item.name }}</el-radio-button>
		</el-radio-group>
		&emsp; -->
		<div style="display: inline-block; float: left; margin-left: 5px;">
			<template v-if="dateType == 'daterange'">
				<!-- 日期 范围选择 -->
				<el-date-picker key="daterange" v-model="dataForm.rangeDate" type="daterange"
					value-format="yyyy-MM-dd HH:mm:ss"
					:picker-options="{ disabledDate: time => !(time.getTime() >= Date.now() - 31 * 8.64e7 && time.getTime() < Date.now() - 8.64e7) }"
					start-placeholder="开始" end-placeholder="结束" style="width: 240px;" @change="datePickerChage"
					:size="moduleSize" />
			</template>
			<template v-else-if="dateType == 'weekrange'">
				<!-- 周 范围选择 -->
				<!-- <el-date-picker
					key="weekrange1"
					v-model="dataForm.dateStart"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateEnd, '>='), 'firstDayOfWeek':1  }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					style="width: 150px;"
					@change="datePickerChage"
					:size="moduleSize"
				/>
				-
				<el-date-picker
					key="weekrange2"
					v-model="dataForm.dateEnd"
					type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateStart, '<') || weekRangeNum(time, dataForm.dateStart), 'firstDayOfWeek':1  }"
					value-format="yyyy-MM-dd"
					placeholder="选择周"
					format="yyyy 第 WW 周"
					style="width: 150px;"
					@change="datePickerChage"
					:size="moduleSize"
				/> -->
				<el-date-picker key="weekrange1" v-model="weekValue1" type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, weekValue2, '>='), 'firstDayOfWeek': 1 }"
					value-format="yyyy-MM-dd" placeholder="选择周" format="yyyy 第 WW 周" style="width: 150px;"
					@change="weekRan" :size="moduleSize" />
				-
				<el-date-picker key="weekrange2" v-model="weekValue2" type="week"
					:picker-options="{ disabledDate: time => datePickerDisable(time, weekValue1, '<') || weekRangeNum(time, dataForm.dateStart), 'firstDayOfWeek': 1 }"
					value-format="yyyy-MM-dd" placeholder="选择周" format="yyyy 第 WW 周" @change="weekRan"
					style="width: 150px;" :size="moduleSize" />
			</template>

			<template v-else-if="dateType == 'monthrange'">
				<!-- <el-date-picker key="monthrange" v-model="dataForm.rangeDate" type="monthrange" placeholder="选择月度"
					:picker-options="{ disabledDate: time => monthDisableCheck(time), onPick: monthOnPick }"
					value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始月度" end-placeholder="结束月度"
					format="yyyy 年 MM 月" style="width: 300px;" :size="moduleSize" @change="datePickerChage(1)" /> -->
				<el-date-picker key="monthrange1" v-model="monthValue1" type="month"
					:picker-options="{ disabledDate: time => datePickerDisable(time, monthValue2, '>=') }"
					value-format="yyyy-MM-dd" placeholder="选择月" format="yyyy-MM" style="width: 150px;"
					@change="monthRan" :size="moduleSize" />
				-
				<el-date-picker key="monthrange2" v-model="monthValue2" type="month"
					:picker-options="{ disabledDate: time => datePickerDisable(time, monthValue1, '<=') }"
					value-format="yyyy-MM-dd" placeholder="选择月" format="yyyy-MM" @change="monthRan"
					style="width: 150px;" :size="moduleSize" />
			</template>

			<template v-else-if="dateType == 'yearrange'">
				<el-date-picker key="yearrange1" v-model="dataForm.dateStart" type="year" placeholder="选择年度"
					
					value-format="yyyy" format="yyyy 年" style="width: 120px;" @change="yearRan" :size="moduleSize" />
				<!-- -
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateEnd, '>=') }"
				<el-date-picker key="dateEnd" v-model="dataForm.dateEnd" type="year" placeholder="选择年度"
					:picker-options="{ disabledDate: time => datePickerDisable(time, dataForm.dateStart, '<=') }"
					value-format="yyyy" format="yyyy 年" style="width: 120px;" @change="yearRan" :size="moduleSize" /> -->
			</template>
		</div>
	</div>
</template>
 
<script>
import cloneDeep from 'lodash/cloneDeep'
import dayjs from 'dayjs'
export default {
	name: 'search-form-date',
	model: {
		prop: 'curData',
		event: 'change'
	},
	props: {
		curData: { required: true, type: Object } /* v-modal 绑定数据... */,
		isHistory: { type: Boolean, default: true } /* 是否可以选择未来时间 */,
		noList: { type: Array, default: () => [] } /* 选择不展示的列表数据 */,
		outObj: { type: Object, default: () => ({ s: 'start', e: 'end', t: 'type' }) } /*, 输出模块字段定义 */,
		moduleSize: { type: String, default: '--' }
	},
	data() {
		var now = new Date();
		return {
			btnList: [
				{ value: 1, name: '按日', dateType: 'daterange' },
				{ value: 2, name: '按周', dateType: 'weekrange' },

				{ value: 3, name: '按月', dateType: 'monthrange' },
				{ value: 4, name: '按年', dateType: 'yearrange' },
				// { value: 5, name: '季度', dateType: 'quarrange' },
				// { value: 6, name: '半年', dateType: 'halfrange' }
			],
			monthValue1: '',
			monthValue2: '',
			curType: 1,
			weekValue1: '',
			weekValue2: '',
			dateType: '',
			monthDisableDate: {},
			dataForm: {
				date: '',
				rangeDate: [],
				dateStart: '',
				dateEnd: '',
			}
		};
	},
	watch: {
		curType: {
			immediate: true,
			handler(newVal, oldVal) {
				if (newVal == 1) this.dateType = `daterange`;
				else if (newVal == 2) this.dateType = `weekrange`;
				else if (newVal == 3) this.dateType = `monthrange`;
				else if (newVal == 4) this.dateType = `yearrange`;
			}
		},

		curData: {
			immediate: true,
			handler(newVal, oldVal) {
				// 外部入参处理
				if (Object.keys(newVal).length != 0) {
					if (newVal.type) this.curType = newVal.type
					if (newVal.dateRange && newVal.dateRange.beginTime) {
						this.dataForm.rangeDate = [newVal.dateRange.beginTime, newVal.dateRange.endTime]
						switch (newVal.type) {
							case 2:
								this.$nextTick(()=>{
									this.weekValue1 = newVal.dateRange.beginTime
									this.weekValue2 = newVal.dateRange.endTime
								})
								break;
							case 3:
							this.$nextTick(()=>{
									this.monthValue1 = dayjs(newVal.dateRange.beginTime).format('YYYY-MM-DD')
									this.monthValue2 = dayjs(newVal.dateRange.endTime).format('YYYY-MM-DD')
								})
								break;
							case 4:
							this.$nextTick(()=>{
									this.dataForm.dateStart = newVal.dateRange.beginTime
									this.dataForm.dateEnd = newVal.dateRange.endTime
								})
								break;
						
							default:
								break;
						}
					} else {
						let data = {}
						var currentDateStamp = new Date().getTime();
						var date = new Date(currentDateStamp - 86400000 * 7); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
						let Y = date.getFullYear() + '-';
						let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
						let D = date.getDate() + ' ';

						var date2 = new Date(currentDateStamp - 86400000 * 1); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
						let Y2 = date2.getFullYear() + '-';
						let M2 = (date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1) + '-';
						let D2 = date2.getDate() + ' ';
						var start = Y + M + D + '00:' + '00:' + '00'
						var end = Y2 + M2 + D2 + '23:' + '59:' + '59'
						this.dataForm.rangeDate = [start + '', end + '']
						this.curData.dateRange.beginTime = start + ''
						this.curData.dateRange.endTime = end + ''
					}
				}
			}
		}
	},
	computed: {
		showBtnList: {
			get() {
				return this.btnList.filter(e => !this.noList.includes(+e.value))
			},
			set(val) {
				this.curType = val[0]['value']
			}
		},
	},
	mounted() {
	},
	created() {
		// this.changeTimeType();
	},
	methods: {
		changeTimeType() {
			let data = {}
			var currentDateStamp = new Date().getTime();
			// if(curType=1){
			data = { start: this.timestampToTime(currentDateStamp - 86400000 * 15), end: this.timestampToTime(currentDateStamp - 86400000 * 1) }
			this.dataForm.start = data.start;
			this.dataForm.end = data.end;
			var returnData = {
				cType: 1,
				beginTime: data.start,
				endTime: data.end,
			}

			this.curData.dateRange.beginTime = data.start
			this.curData.dateRange.endTime = data.end
			this.dataForm.rangeDate = [this.curData.dateRange.beginTime, this.curData.dateRange.endTime]
			this.$emit('child', returnData)
		},
		clear() {
			this.dataForm = cloneDeep(this.$options.data().dataForm);

			this.$emit('change', { type: this.curType, dateRange: null });
		},
		timestampToTime(timestamp) {
			var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
			let Y = date.getFullYear() + '-';
			let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			let D = date.getDate() + ' ';
			return Y + M + D + '' + '00:' + '00:' + '00';
		},
		weekRan() {
			let data = {}
			if (this.weekValue1) data.start = this.getFirstDayOfWeek2(new Date(this.weekValue1))
			if (this.weekValue2) data.end = this.getFirstDayOfWeek1(new Date(this.weekValue2))
			var returnData = {
				cType: 2,
				beginTime: data.start,
				endTime: data.end,
			}
			// if (!data.start && !data.end) {
			// 	returnData.beginTime = ''
			// 	returnData.endTime = ''
			// }
			this.$emit('child', returnData);

		},
		//type为字符串类型，有两种选择，"s"代表开始,"e"代表结束，dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
		getweeks(type, dates) {
			var now = new Date();
			var nowTime = now.getTime();
			var day = now.getDay();
			var longTime = 24 * 60 * 60 * 1000;
			var n = longTime * 7 * (dates || 0);
			if (type == "s") {
				var dd = nowTime - (day - 2) * longTime + n;
			};
			if (type == "e") {
				var dd = nowTime + (7 - day) * longTime + n;
			};
			dd = new Date(dd);
			var y = dd.getFullYear();
			var m = dd.getMonth() + 1;
			var d = dd.getDate();
			m = m < 10 ? "0" + m : m;
			d = d < 10 ? "0" + d : d;
			var day = y + "-" + m + "-" + d;
			return day;
		},
		yearRan() {
			var returnData = {
				cType: 4,
				beginTime: this.dataForm.dateStart ? this.dataForm.dateStart + '-01-01 00:00:00' : '',
				endTime: this.dataForm.dateStart ? this.dataForm.dateStart + '-12-31 23:59:59' : '',
			}
			// }
			this.$emit('child', returnData);
		},
		monthRan() {
			var returnData = {
				cType: 3,
				beginTime: this.monthValue1 ? this.monthValue1 + ' 00:00:00' : '',
				// endTime: this.monthValue2 ? dayjs(this.monthValue2).format + ' 23:59:59' : '',
				endTime:this.monthValue2 ?dayjs(this.monthValue2).endOf('month').format('YYYY-MM-DD HH:mm:ss'):''
			}
			console.log(returnData,'dagedage')
			this.$emit('child', returnData);
		},
		getMonthEndDay(time){
			return dayjs(time).endOf('month')
		},

		/* 12周数量限制 */
		weekRangeNum(time, date) {
			if (!date) return false;
			if (time.getTime() > new Date(date).getTime() + 8.64e7 * 85) return true;
			return false;
		},
		/* start使用  >=;   end  < */
		/* 参数中不应用 >= 或 < 符号. 应用参数传入的位置不同来控制参数 */
		datePickerDisable(time, date, com = '>=') {
			if (this.isHistory && time.getTime() > Date.now()) return true;
			if(((time.getTime()-dayjs(date).valueOf())>31104000000)||((dayjs(date).valueOf()-dayjs(time).startOf('week').valueOf())>31104000000)||(dayjs(date).valueOf()-dayjs(time).subtract(1,'day').startOf('week').valueOf())>31104000000){
				return true
			}
			// if(((time.getTime()-dayjs(date).valueOf())>31104000000)||((dayjs(date).valueOf()-time.getTime())>31104000000)){
				
			// 	return true
			// }
			if (com == '>=') {
				// 开始周
			}
			if (date) {
				if (com == '>=') {
					// 开始周
					let endDate = this.getFirstDayOfWeek1(new Date(date))
					return eval(`${time.getTime()} ${com} ${new Date(endDate).getTime()}`);
				} else {
					// 结束周
					let startDate = this.getFirstDayOfWeek2(new Date(date))
					return eval(`${time.getTime()} ${com} ${new Date(startDate).getTime()}`);
				}
			}
			return false;
		},
		outMonth() {
			var { monthDateS = 1, monthDateE } = this.dataForm;
			var mOptions = { 1: '01-01', 2: '04-01', 3: '07-01', 4: '10-01' },
				mEndOptions = { 1: '03-31', 2: '06-30', 3: '06-30', 4: '12-31' },
				yOptions = { 1: '01-01', 2: '07-01' },
				yEndOptions = { 1: '06-30', 2: '12-31' };
			var s, e;

			if (!monthDateS) monthDateS = 1;

			return { s, e };
		},
		datePickerChage(int) {
			/* 当前数据变化 */
			var data = {};
			var cType = this.curType;
			var { date = '', dateStart = '', dateEnd = '', rangeDate = [], monthDateS, monthDateE } = this.dataForm;
			var monthDate = this.outMonth();

			/* 准备重构数据整合............  可复用性高. */
			/* 1: 单日,2: 单周,3: 年度,4: 月度,99: 自定义 */
			/* 判断是否是范围选择 */
			if (cType == 1 && rangeDate) {
				data = { start: rangeDate[0], end: rangeDate[1] };
			} else if (cType == 2) {
				if (dateStart) data.start = this.getFirstDayOfWeek(new Date(dateStart));
				if (dateEnd) data.end = this.getFirstDayOfWeek(new Date(dateEnd));
				// data = { start: dateStart, end: dateEnd };
			} else if (cType == 4) {
				if (dateStart) data.start = `${dateStart}-01-01 00:00:00`
				if (dateEnd) data.end = `${dateEnd}-01-01 00:00:00`
			} else if (cType == 3 && rangeDate) {

				if (int) {
					var mon = rangeDate[1].slice(5, 7)
					var year = rangeDate[1].slice(0, 4)
					var lastDay = new Date(year, mon, 0).getDate()
					rangeDate[1] = year + '-' + mon + '-' + lastDay + ' 00:00:00'
				}

				data = { start: rangeDate[0], end: rangeDate[1] };

			}
			var outData = {
				...this.curData,
				dateRange: { beginTime: data.start, endTime: data.end }
			};
			var returnData = {
				cType: this.curType,
				beginTime: data.start,
				endTime: data.end,
			}
			this.dataForm.dateStart = data.start
			this.dataForm.dateEnd = data.end

			if (data.start && data.end) this.$emit('searchFinish', outData);
			this.$emit('change', outData);
			this.$emit('child', returnData);

		},
		monthDisableCheck(time) {
			if (this.isHistory && time.getTime() > Date.now()) return true;
			var { minDate } = this.monthDisableDate
			if (minDate) {
				var cur = new Date(minDate).getTime()
				var timeN = time.getTime()

				var month12 = 365 * 8.64e7;
				if (cur - month12 + 31 * 8.64e7 >= timeN) return true
				else if (cur + month12 - 30 * 8.64e7 < timeN) return true
			}

			return false;
		},
		getFirstDayOfWeek(date) {
			var day = date.getDay() || 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00`
		},
		getFirstDayOfWeek1(date) {
			var day = date.getDay() || 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7 - day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 23:59:59`
		},
		getFirstDayOfWeek2(date) {
			var day = date.getDay() || 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00`
		},
		getFirstDayOfWeek3(date) {
			var day = date.getDay() || 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7 - day);
			return `${out.getFullYear()}-${out.getMonth() + 2}-${out.getDate()} 00:00:00`
		},
		getFirstDayOfWeek4(date) {
			var day = date.getDay() || 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1);
			return `${out.getFullYear()}-${out.getMonth() + 2}-${out.getDate()} 00:00:00`
		},
		getFirstDayOfWeek5(date) {
			var day = 7;
			var out = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
			return `${out.getFullYear()}-${out.getMonth() + 1}-${out.getDate()} 00:00:00`
		},
		monthOnPick(date) {
			if (!date.mxaDate) this.monthDisableDate = date
			else this.monthDisableDate = {}
		},
		reset() {
			this.curType = 1;
			this.changeTimeType();
			this.curData.dateRange.beginTime = this.dataForm.start + '';
			this.curData.dateRange.endTime = this.dataForm.end + '';

		},
		//获取本周
		getWeekDays(date) {
			let firstDay = new Date(date.getFullYear(), 0, 1)
			let dayOfWeek = firstDay.getDay()
			let spendDay = 1
			if (dayOfWeek != 0) {
				spendDay = 7 - dayOfWeek + 1
			}
			firstDay = new Date(val.getFullYear(), 0, 1 + spendDay)
			let d = Math.ceil((val.valueOf() - firstDay.valueOf()) / 86400000)
			let result = Math.ceil(d / 7)
			let year = val.getFullYear()
			let week = result + 2
			return year + '第' + week + '周'
		},
		//获取本月

		/* 单选change */
		radioChange() {
			this.dataForm.rangeDate = []
			let data = {}
			// var date=new Date()
			var date = new Date()
			var nowTime = date.getTime();
			var day = date.getTime() || 7;
			var y = date.getFullYear()
			var m = date.getMonth() + 1
			var d = date.getDate()
			var week = y + '-' + m + '-' + d + ' ' + '00' + ':' + '00' + ':' + '00'
			var monthStart = y + '-' + m + '-' + '01' + ' ' + '00' + ':' + '00' + ':' + '00'
			var monthEnd = y + '-' + m + '-' + d + ' ' + '00' + ':' + '00' + ':' + '00'

			if (this.curType == 1) {
				this.changeTimeType()
			} else if (this.curType == 2) {
				this.weekValue1 = this.getweeks("s", -1),
					this.weekValue2 = this.getweeks("e", -1),
					this.weekRan()
			} else if (this.curType == 3) {
				// data.start =monthStart
				// data.end = monthEnd
				this.dataForm.rangeDate[0] = monthStart;
				this.dataForm.rangeDate[1] = monthEnd
				this.datePickerChage()
			} else if (this.curType == 4) {
				this.dataForm.dateStart = y + ''
				this.dataForm.dateEnd = y + ''
				this.yearRan()
			}
			this.$emit('change', { ...this.curData, [this.outObj.t]: this.curType })
			// this.clear()
		}
	}
};
</script>
 
<style lang="scss">
.el-select .el-input {
	width: 100% !important;
}
</style>
 